package com.wisedu.mobile.manage.controller;

import com.wisedu.mobile.auth.service.impl.v1.db.SysMenuServiceImpl;
import com.wisedu.mobile.auth.service.impl.v1.db.SysRoleServiceImpl;
import com.wisedu.mobile.common.AjaxResult;
import com.wisedu.mobile.common.BaseController;
import com.wisedu.mobile.common.domain.SysMenu;
import com.wisedu.mobile.common.domain.SysRole;
import org.nutz.castor.Castors;
import org.nutz.dao.entity.Record;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: hj
 * @Date: 2020/3/24 下午4:28
 */
@RestController
@RequestMapping("/manage/sys/role")
public class SysRoleController extends BaseController<SysRole> {

    @Autowired
    SysMenuServiceImpl sysMenuService;

    @Autowired
    SysRoleServiceImpl sysRoleService;

    @PostMapping("tree")
    public AjaxResult<List<SysMenu>> tree(String roleid) {
        List<SysMenu> res = new ArrayList<>();
        List<Record> records = sysMenuService.selectMenuByRole(roleid);
        for(Record r:records) {
            res.add(Lang.map2Object(r,SysMenu.class));
        }
        return AjaxResult.success(sysMenuService.buildMenuTree(res));
    }

    @PostMapping("saveRoleMenu")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveRoleMenu(String roleid,String menuIdList) {
        SysRole role = sysRoleService.fetch(roleid);
        sysRoleService._clearLinks(role,"menus");
        String[] menuids = menuIdList.split(",");
        List<SysMenu> menus = new ArrayList<>();
        for(String menuid:menuids){
            SysMenu menu = new SysMenu();
            menu.setId(menuid);
            menus.add(menu);
        }
        role.setMenus(menus);
        sysRoleService.insertRelation(role,"menus");
        return AjaxResult.success();
    }
}
